package com.feiyu.auth.granter;

import com.feiyu.auth.util.AuthCode;
import com.feiyu.auth.util.TokenUtil;
import com.feiyu.common.cache.CacheNames;
import com.feiyu.common.exception.GlobalException;
import com.feiyu.user.entity.UserInfo;
import com.feiyu.user.feign.UserFeignClient;
import lombok.AllArgsConstructor;
import org.springblade.core.tool.utils.*;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Component;
import javax.servlet.http.HttpServletRequest;

/**
 * 密码授权
 * @author tang ming
 * @since 2021/12/5 9:35
 */
@Component
@AllArgsConstructor
public class CaptchaTokenGranter implements TokenGranter {

	public static final String GRANT_TYPE = "captcha";

	private UserFeignClient userFeignClient;

	private PasswordEncoder passwordEncoder;

	private RedisUtil redisUtil;

	@Override
	public UserInfo grant(TokenParameter tokenParameter) {
		HttpServletRequest request = WebUtil.getRequest();

		String key = request.getHeader(TokenUtil.CAPTCHA_HEADER_KEY);
		String code = request.getHeader(TokenUtil.CAPTCHA_HEADER_CODE);
		// 获取验证码
		String redisCode = String.valueOf(redisUtil.get(CacheNames.CAPTCHA_KEY + key));
		// 判断验证码
		if (code == null || !StringUtil.equalsIgnoreCase(redisCode, code)) {
			throw new GlobalException(AuthCode.CODE_ERROR);
		}

		String account = tokenParameter.getStr("account");
		String password = tokenParameter.getStr("password");
		UserInfo userInfo = null;
		//、参数不为空 进行验证流程
		if(Func.isNoneBlank(account,password)) {
			// 从用户服务获取登录的用户信息
			UserInfo result = userFeignClient.userInfo(account).getData();
			//验证密码正确性
			if (result != null && passwordEncoder.matches(password, result.getPassword()))
				userInfo = result;
		}
		return userInfo;
	}

}
